package com.wei.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.wei.entity.Member;
import com.wei.service.MemberService;
import com.wei.util.ConstantWxUtils;
import com.wei.util.HttpClientUtils;
import com.wei.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author wjx
 * @ClassName WxApiController
 * @description: TODO
 * @date 2022-12-04 02:41
 * @version: 1.0
 */
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private MemberService memberService;

    @GetMapping("/login")
    public String getWxCode() {
        //请求微信的一个地址

        // 微信开放平台授权baseUrl 固定写法
        // 固定地址：https://open.weixin.qq.com/connect/qrconnect
        // 参数后面加 %s，表示一个占位符，需要传参。
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";

        String redirectUri = ConstantWxUtils.WX_OPEN_REDIRECT_URL;

        try {
            redirectUri = URLEncoder.encode(redirectUri, "utf-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        String requestUrl = String.format(
                baseUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                redirectUri,
                "atguigu");

        return "redirect:" + requestUrl;
    }

    //请求地址：localhost:8006/eduucenter/member/login，扫码后，
    // 会重定向：http://localhost:8006/api/ucenter/wx/callback?code=081jU8200zNLyO1KTi300C6VKN2jU82A&state=atguigu
    // 所以，我们需要把访问端口号改为“8006”,然后在控制层的路径为“/api/ucenter/wx”,调用callback方法,可以看到路径拼接值，所以是get提交

    @GetMapping("/callback")
    public String callback(String code, String state) {

//        System.out.println(code);  //081jU8200zNLyO1KTi300C6VKN2jU82A
//        System.out.println(state);

        //拿着获取到的code值（临时票据），请求微信提供固定的地址。获取到两个值：accessToken 和 openId
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +
                "&secret=%s" +
                "&code=%s" +
                "&grant_type=authorization_code";

        String accessTokenUrl = String.format(
                baseAccessTokenUrl,
                ConstantWxUtils.WX_OPEN_APP_ID,
                ConstantWxUtils.WX_OPEN_APP_SECRET,
                code
        );

        try {
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);

            //{"access_token":"60_XASMADCDkHyWwaLdNQrzDgiD89ZQdySOKuiIOVRNuvKDaWcJESQVpyqXsvItdwMH8FH0lFZxgonYYKU3_FidA0372eDD90EiOFe-HppziIU",
            // "expires_in":7200,
            // "refresh_token":"60_8Mbu0Xr4v-NDMDYWkOgr4DmjKS5L06aKKnHqbrh4viXZMA7Ji-mciVtEoE5yxvpFdVNGqFEvn7c84B4tp4uFNQiYArvimvEfpy1nrVO77-c",
            // "openid":"o3_SC54AFSt5JKqaOJepH-6SmX8w",
            // "scope":"snsapi_login","unionid":"oWgGz1Mf16ONGvP5cSZA3H8wEYYs"}
//            System.out.println(accessTokenInfo);

            //拿到 openid 和 accessToken
            JSONObject jsonObject = JSONUtil.parseObj(accessTokenInfo);
            String accessToken = jsonObject.getStr("access_token");
            String openid = jsonObject.getStr("openid");

            //将扫码人的信息加入数据库

            //用openid判断数据库是否有此信息
            Member member = memberService.getUserInfo(openid);

            if (member == null) {

                //3.拿到得到 access_token 和 openid 再去请求微信提供固定的地址，获取到扫描人信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";

                String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);

                String userInfo = HttpClientUtils.get(userInfoUrl);

                /*
                {"openid":"o3_SC54AFSt5JKqaOJepH-6SmX8w",
                    "nickname":"random",
                    "sex":0,"language":"",
                    "city":"","province":"","country":"",
                    "headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/eXtnhgc630kUTYW6Oj5nOCZsCpHYsiacBAia0nC6a8ycCfxSVu3w6PJ23scBMYnYULW20ibrBlHe9kibTXrokJBXWg\/132",
                    "privilege":[],"unionid":"oWgGz1Mf16ONGvP5cSZA3H8wEYYs"}
                 */
//                System.out.println(userInfo);

                JSONObject userInfoJson = JSONUtil.parseObj(userInfo);

                String nickname = userInfoJson.getStr("nickname");
                String avatar = userInfoJson.getStr("headimgurl");

                member = new Member();

                member.setOpenid(openid);
                member.setNickname(nickname);
                member.setAvatar(avatar);

                memberService.save(member);
            }

            //存在则直接从数据库取数据
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            return "redirect:http://localhost:3000?token=" + token;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
